<template>
  <div class="nursing-container">
    <!-- 查询 -->
    <div class="search-container">
      <!-- 查询条件下拉框 -->
      <el-select
          v-model="queryCondition"
          placeholder="请选择查询条件"
          style="width: 150px"
          class="search-select"
      >
        <el-option label="名称" value="nursingName"></el-option>
        <el-option label="编号" value="serialNumber"></el-option>
        <el-option label="护理级别" value="level"></el-option> <!-- 添加护理级别选项 -->
      </el-select>
      <!-- 输入查询内容（护理级别时此输入框不填，其他条件填） -->
      <el-input
          placeholder="请输入查询内容"
          v-model="queryValue"
          style="width: 200px"
          class="search-input"
      ></el-input>
      <el-button
          @click="queryByName"
          type="success"
          plain
          class="search-button"
      >
        查询
      </el-button>
      <el-button
          @click="showNursingDialog"
          type="primary"
          class="register-button"
      >
        添加
      </el-button>
    </div>

    <!-- 错误信息 -->
    <div class="error-message">{{ errorMessage }}</div>

    <!-- 护理项目信息表格 -->
    <el-table
        :data="nursingList"
        class="nursing-table"
        header-cell-class-name="table-header"
    >
      <!-- 表格列不变 -->
      <el-table-column label="序号" type="index" width="60px" align="center"></el-table-column>
      <el-table-column prop="serialNumber" label="编号" width="100px" align="center"></el-table-column>
      <el-table-column prop="nursingName" label="名称" width="120px" align="center"></el-table-column>
      <el-table-column prop="servicePrice" label="价格" width="100px" align="center"></el-table-column>
      <el-table-column prop="executionCycle" label="执行周期" width="100px" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="100px" align="center">
        <template #default="scope">
          {{ scope.row.status === 1? "启用" : "停用" }}
        </template>
      </el-table-column>
      <el-table-column prop="executionTimes" label="执行次数" width="100px" align="center"></el-table-column>
      <el-table-column prop="message" label="描述" width="200px" align="center"></el-table-column>
      <el-table-column label="操作" width="160px" align="center">
        <template #default="scope">
          <el-button
              type="primary"
              size="small"
              @click="showEditDialog(scope.row.id)"
              class="edit-button"
          >
            修改
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="toggleStatus(scope.row.id, scope.row.status)"
              class="delete-button"
          >
            {{ scope.row.status === 1 ? '停用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          background
          v-model:current-page="pageContains.pageNum"
          v-model:page-size="pageContains.pageSize"
          :page-sizes="[10, 20, 30, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageContains.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          class="pagination"
      />
    </div>

    <!-- 护理项目信息对话框 -->
    <el-dialog
        v-model="nursingDialog"
        :title="dialogTitle"
        class="nursing-dialog"
    >
      <el-form :model="curNursing" class="nursing-form">
        <el-form-item label="编号" class="form-item">
          <el-col :span="11">
            <el-input v-model="curNursing.serialNumber" class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="名称" class="form-item">
          <el-col :span="11">
            <el-input v-model="curNursing.nursingName" class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="价格" class="form-item">
          <el-col :span="11">
            <el-input v-model="curNursing.servicePrice" class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="描述" class="form-item">
          <el-col :span="11">
            <el-input v-model="curNursing.message" class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="状态" class="form-item">
          <el-col :span="11">
            <el-select v-model="curNursing.status" class="form-select">
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="2"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="执行周期" class="form-item">
          <el-col :span="11">
            <el-input v-model="curNursing.executionCycle" class="form-input"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="执行次数" class="form-item">
          <el-col :span="11">
            <el-input v-model="curNursing.executionTimes" class="form-input"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="optOne()" class="dialog-button">{{ buttonOpt }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import http from '@/axios/http.js';
import qs from "qs";
import { useRoute } from 'vue-router';

const route = useRoute();
console.log(route.query.levelId); // 获取传递的levelId
console.log(route.query.levelName); // 获取传递的levelName
// 存放护理项目数据集合
let nursingList = ref([]);
// 报错提示
let errorMessage = ref("");
// 查询条件（名称、编号、护理级别）
let queryCondition = ref("nursingName"); // 默认选择名称
// 输入的查询值（护理级别时不使用，其他条件使用）
let queryValue = ref("");
// 护理级别查询参数（整合到下拉框后，此处可移除，但保留兼容旧逻辑，实际使用queryCondition判断）
let queryLevel = ref(""); // 实际使用中，当queryCondition为'level'时，用queryValue接收护理级别值，可逐步移除queryLevel
// 对话框显示控制
let nursingDialog = ref(false);
// 护理项目信息
let curNursing = ref({});
// 对话框标题和按钮文字
let dialogTitle = reactive("");
let buttonOpt = reactive("");
// 对话框操作类型
let dialogOptType = reactive(1);
// 护理级别选项（保留用于初始化下拉框，实际查询条件下拉框已整合护理级别）
let levelOptions = ref([
  { label: '请选择', value: '' },
  { label: '一级', value: '一级' },
  { label: '二级', value: '二级' },
  { label: '三级', value: '三级' }
]);
// 分页相关
let pageContains = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 页面初始化（获取护理级别选项，用于下拉框显示）
onMounted(() => {
  http.post('/lyy/get_all_nurse_levels')
      .then((res) => {
        if (res.data.result === 'success') {
          const levelOptionsData = res.data.data.map(item => ({
            label: item.levelId,
            value: item.levelId
          }));
          levelOptionsData.unshift({ label: '请选择', value: '' });
          levelOptions.value = levelOptionsData;
        }
      })
      .catch((error) => {
        console.error('获取护理级别出错:', error);
      });
  getAllNursingProjects();
});

// 执行查询
function queryByName() {
  let param = {};
  if (queryCondition.value) {
    if (queryCondition.value === 'level') { // 护理级别查询
      param[queryCondition.value] = queryValue.value; // 护理级别值通过queryValue输入
    } else { // 名称、编号等其他条件
      param[queryCondition.value] = queryValue.value;
    }
  }
  param.pageNum = pageContains.value.pageNum;
  param.pageSize = pageContains.value.pageSize;

  http.post('/lyy/get_nursing_projects_by', qs.stringify(param))
      .then((res) => {
        console.log('查询护理项目响应:', res);
        let result = res.data;
        if (result.result === 'success') {
          pageContains.value = {
            pageNum: result.data.pageNum,
            pageSize: result.data.pageSize,
            total: result.data.total
          };
          nursingList.value = result.data.list;
        } else {
          errorMessage.value = result.error;
        }
      })
      .catch((error) => {
        console.error('查询护理项目出错:', error);
        errorMessage.value = '网络请求出错，请稍后重试';
      });
}

// 获取所有护理项目信息
function getAllNursingProjects() {
  let params = {
    pageNum: pageContains.value.pageNum,
    pageSize: pageContains.value.pageSize
  };

  http.post('/lyy/get_all_nursing_projects', qs.stringify(params))
      .then((res) => {
        console.log('获取所有护理项目响应:', res);
        let result = res.data;
        if (result.result === 'success') {
          nursingList.value = result.data.list;
          pageContains.value = {
            pageNum: result.data.pageNum,
            pageSize: result.data.pageSize,
            total: result.data.total
          };
        } else {
          errorMessage.value = result.error;
        }
      })
      .catch((error) => {
        console.error('获取所有护理项目出错:', error);
        errorMessage.value = '网络请求出错，请稍后重试';
      });
}

// 显示添加对话框
function showNursingDialog() {
  nursingDialog.value = true;
  dialogTitle = "添加护理项目";
  buttonOpt = "添加";
  dialogOptType = 1;
  curNursing.value = {};
}

// 记录护理项目信息
function recordOne() {
  let param = curNursing.value;
  http.post('/lyy/add_one_nursing_project', param)
      .then((res) => {
        let result = res.data;
        if (result.result === 'success') {
          closeNursingDialog();
          getAllNursingProjects();
        } else {
          errorMessage.value = result.error;
        }
      })
      .catch((error) => {
        console.error('添加护理项目出错:', error);
        errorMessage.value = '网络请求出错，请稍后重试';
      });
}

// 显示编辑对话框
function showEditDialog(id) {
  getNursingInfo(id);
  nursingDialog.value = true;
  dialogTitle = "护理项目信息修改";
  buttonOpt = "修改";
  dialogOptType = 2;
}

function getNursingInfo(id) {
  let param = { id: id };
  http.post('/lyy/get_nursing_project_by_id', qs.stringify(param))
      .then((res) => {
        let result = res.data;
        if (result.result === 'success') {
          curNursing.value = result.data;
        } else {
          errorMessage.value = result.error;
        }
      })
      .catch((error) => {
        console.error('获取护理项目信息出错:', error);
        errorMessage.value = '网络请求出错，请稍后重试';
      });
}

// 切换护理项目状态
function toggleStatus(id, currentStatus) {
  http.post('/lyy/toggle_nursing_project_status', qs.stringify({ id }))
      .then((res) => {
        if (res.data.result === 'success') {
          ElMessage.success('状态切换成功');
          getAllNursingProjects(); // 刷新列表
        } else {
          ElMessage.error(res.data.error || '操作失败');
        }
      })
      .catch((error) => {
        console.error('状态切换失败:', error);
        ElMessage.error('网络请求失败');
      });
}

// 编辑护理项目信息
function editOne() {
  let param = curNursing.value;
  http.post('/lyy/modify_nursing_project_by_id', param)
      .then((res) => {
        let result = res.data;
        if (result.result === 'success') {
          closeNursingDialog();
          getAllNursingProjects();
        } else {
          errorMessage.value = result.error;
        }
      })
      .catch((error) => {
        console.error('修改护理项目出错:', error);
        errorMessage.value = '网络请求出错，请稍后重试';
      });
}

// 操作按钮
function optOne() {
  if (dialogOptType === 1) {
    recordOne();
  } else if (dialogOptType === 2) {
    editOne();
  }
}
// 关闭对话框
function closeNursingDialog() {
  nursingDialog.value = false;
  curNursing.value = {};
}

// 分页处理
const handlePageChange = (pageNum1) => {
  pageContains.value.pageNum = pageNum1;
  getAllNursingProjects();
};

const handleSizeChange = (pageSize1) => {
  pageContains.value.pageSize = pageSize1;
  getAllNursingProjects();
};
</script>
<style scoped>
.nursing-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  margin-right: 10px;
}

.search-button {
  margin-right: 20px;
}

.register-button {
  width: 100px;
  font-weight: bold;
  font-size: 16px;
}

.error-message {
  color: #f56c6c;
  margin-bottom: 20px;
  text-align: center;
}

.nursing-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.table-header {
  background-color: #f0f2f5;
  font-weight: bold;
  color: #333;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination {
  width: 100%;
}

.nursing-dialog {
  width: 500px;
}

.nursing-form {
  width: 100%;
}

.form-item {
  margin-bottom: 20px;
}

.form-input,
.form-select {
  width: 100%;
}

.dialog-footer {
  text-align: center;
  margin-top: 20px;
}

.dialog-button {
  width: 100%;
  padding: 10px;
}
</style>